<template>
	<el-form size="large" class="login-content-form">
		<el-form-item class="login-animation1">
			<el-input text placeholder="请输入账号" v-model="state.ruleForm.userName" clearable autocomplete="off">
				<template #prefix>
					<i class="iconfont icon-user" />
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2">
			<el-input
				type="password"
				placeholder="请输入密码"
				v-model="state.ruleForm.password"
				autocomplete="off"
				show-password
			>
				<template #prefix>
					<i class="iconfont icon-unlock" />
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit" v-waves @click="onSignIn" :loading="state.loading.signIn">
				<span>登 录</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts" name="loginAccount">
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import Cookies from '/@/utils/Cookies';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { NextLoading } from '/@/utils/loading';
import api from '/@/api/login/index';
import imAPI from '/@/api/im/index';
import { Local } from '/@/utils/storage';
import { useIMStore } from '/@/stores/im'
import commonApi from '/@/api/common';

// 
const router = useRouter();
const state = reactive({
	ruleForm: {
		userName: '',
		password: '',
	},
	loading: {
		signIn: false,
	},
});
const imStore = useIMStore()

// UserSig 
async function generateUserSig() {
  try {
    // UserSig 
    const response = await imAPI.getUserSign()
    console.log('response:', response)
    if (response.data && response.data.userSig) {
      return {
        userSig: response.data.userSig,
        sdkAppID: response.data.sdkAppId,
        userID: response.data.userId,
      }
    }
  }
  catch (error) {
    console.warn('UserSig ,', error)
  }

  // UserSig 
  const account = Local.get('userId');
  if (account) {
    const storedConfig = localStorage.getItem(`im_config_${account}`)
    if (storedConfig) {
      try {
        return JSON.parse(storedConfig)
      } catch (error) {
        console.warn('IM ,', error)
      }
    }
  }

  // ,UserSig 
  throw new Error('UserSig ,IM ')
}

// IM 
async function autoLoginIM(account:any) {
  try {
    const imConfigInfo = await generateUserSig()
    console.log('imConfigInfo:', imConfigInfo)

    // SDK AppID,IM 
    if (!imConfigInfo.sdkAppID) {
      console.warn('IM SDK AppID ,IM ')
      return
    }

    // IM ,localStorage
    try {
      localStorage.setItem(`im_config_${account}`, JSON.stringify(imConfigInfo))
    }
    catch (error) {
      console.warn('IM ,', error)
    }

    // IM SDK
    const initResult = await imStore.initIM(imConfigInfo.sdkAppID)
    console.log ('initResult:', initResult)
    if (initResult.code !== 0) {
      console.error('IM SDK ,', initResult.message)
      return
    }

    const userID = imConfigInfo.userID.toString()
    const userSig = imConfigInfo.userSig

    // IM 
    const loginResult = await imStore.login(userID, userSig)
    if (loginResult.code === 0) {
      // 设置待处理的用户信息，等待SDK Ready事件
		commonApi.getUserInfo().then((res:any) => {
			if (res.code === 200) {
				imStore.setPendingUserInfo({
					nick: res.user.nickName, // 使用登录用户名作为昵称
					selfSignature: `我是${res.user.nickName}`, // 设置个性签名
					avatar: res.user.avatar, // 如果有头像URL可以在这里设置
				})
			}
		})
    }
    else {
      console.error('IM ,', loginResult.message)
      ElMessage.warning(`IM ,: ${loginResult.message}`)
    }
  }
  catch (error) {
    console.error('IM ,', error)
    ElMessage.warning('IM ,IM ')
  }
}

// 
const onSignIn = async () => {
	if(!state.ruleForm.userName) {
		return ElMessage.error('')
	}
	if(!state.ruleForm.password) {
		return ElMessage.error('')
	}
	state.loading.signIn = true;
	try {
		const res = await api.signIn({
			username: state.ruleForm.userName,
			password: state.ruleForm.password,
			source: 'business',
		});
		console.log(':', res)
		if(res.code === 200) {
			const data = res.data;
			
			// token 
			Cookies.set('token', data.access_token);
			Cookies.set('userId', data.userid);
			Cookies.set('userName', state.ruleForm.userName);
			// ,IM 
			await autoLoginIM(data.userid)
			const isNoPower = await initFrontEndControlRoutes();
			signInSuccess(isNoPower);
		}	
	} catch (error) {
		state.loading.signIn = false;
	}
};
// 
const signInSuccess = (isNoPower: boolean | undefined) => {
	if (isNoPower) {
		ElMessage.warning('');
		Cookies.clear();
	} else {
		// 
		NextLoading.start();
		router.push({
			path: '/home'
		});
	}
	state.loading.signIn = false;
};
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 60px;
	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}
	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;
		&:hover {
			color: #909399;
		}
	}
	.login-content-code {
		width: 100%;
		padding: 0;
		font-weight: bold;
		letter-spacing: 5px;
	}
	.login-content-submit {
		width: 100%;
		--el-button-size: 46px;
		letter-spacing: 2px;
		font-weight: 400;
		margin-top: 15px;
		font-size: 20px;
	}
}
</style>
